import {
  KeywordModel
} from '../../models/keyword'
import {
  paginationBev
} from '../behaviors/pagination.js'

import {
  BookModel
} from '../../models/book'

const keywordModel = new KeywordModel()
const bookModel = new BookModel()
Component({
  /**
   * 组件的属性列表
   */
  behaviors: [paginationBev],
  properties: {
    more: {
      type: String,
      observer: 'loadMore'
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    historyWords: [],
    hotWords: [],
    searching: false,
    q: '',
    loading: false,
    loadingCenter: false
  },
  attached() {
    const historyWords = keywordModel.getHistory()
    const hotWords = keywordModel.getHot()
    this.setData({
      historyWords
    })
    hotWords.then(res => {
      this.setData({
        hotWords: res.hot
      })
    })

  },

  /**
   * 组件的方法列表
   */
  methods: {
    loadMore() {
      if (!this.data.q) {
        return
      }
      if (this.data.loading) {
        return
      }
      if (this.hasMore()) {
        this.setData({
          loading:true
        })
        bookModel.search(this.getCurrentStart(), this.data.q).then(res => {
          this.setMoreData(res.books)
          this.setData({
            loading:false
          })
        }, () => {
          this.setData({
            loading:false
          })
        })
      }
    },
    onCancel(e) {
      this.init()
      this.triggerEvent('cancel')
      if (wx.pageScrollTo) {
        wx.pageScrollTo({
          scrollTop: 0,
          duration: 0
        })
      }
    },
    onDelete() {
      this.init()
      this.setData({
        searching: false,
        q: ''
      })
    },
    onConfirm(e) {
      this.setData({
        searching: true
      })
      this._showLoadingCenter()
      const q = e.detail.value || e.detail.text
      bookModel.search(0, q).then(res => {
        this.setMoreData(res.books)
        this.setTotal(res.total)
        this.setData({
          q
        })
        keywordModel.addToHistory(q)
        this._hideLoadingCenter()
      })
    },
    _showLoadingCenter() {
      this.setData({
        loadingCenter: true
      })
    },
    _hideLoadingCenter() {
      this.setData({
        loadingCenter: false
      })
    }
  }
})